<script lang="ts" setup>
import lodash from 'lodash'
import moment from 'moment'
import { Tag } from 'vant'
import { JobRecordApi } from '~/api/JobRecordApi'
import { ContactModel } from '~/model'
import { JobAction, JobRecordModel } from '~/model/JobRecordModel'
import { ScheduleModel } from '~/model/ScheduleModel'
import { SalaryModel } from '~/model/SalaryModel'

const route = useRoute()
const router = useRouter()

enum Mode {
  None,
  Day,
  Night,
  NoSchedule,
  LeftUnsettled,
  LeftSettled,
}

const mode = ref(Mode.None)

const records = ref([] as JobRecordModel[])

onMounted(() => {
  JobRecordApi.getAll()
    .then((res) => {
      records.value = res
      records.value.sort((a, b) => b.id - a.id)
    })

  mode.value = getModeByName(route.query.mode as string)
  // if (route.query.day) {
  //   mode.value = Mode.Day
  // }
  // else if (route.query.night) {
  //   mode.value = Mode.Night
  // }
  // else if (route.query.no_schedule) {
  //   mode.value = Mode.NoSchedule
  // }
  // else if (route.query.left) {
  //   mode.value = Mode.Left
  // }
})

const recordsGrouped = computed(() => lodash.groupBy(records.value, x => x.worker?.id))
const scheduleModels = computed(() => {
  return Object.values(recordsGrouped.value).map(arr => new ScheduleModel(arr))
})
const salaryModels = computed(() => {
  return Object.values(recordsGrouped.value).map(arr => new SalaryModel(arr))
})

// 白班工人
const dayWorkers = computed(() => {
  return scheduleModels.value.filter(x => x.getSchedule() === '白班').map(x => x.worker())
})

// 夜班工人
const nightWorkers = computed(() => scheduleModels.value.filter(x => x.getSchedule() === '夜班').map(x => x.worker()))

// 其他工人
const otherWorkers = computed(() => {
  const models = scheduleModels.value.filter((x) => {
    return !x.left() && x.getSchedule() !== '白班' && x.getSchedule() !== '夜班'
  })
  return models.map(x => x.worker())
})

// 离职工人
const leftWorkers = computed(() => scheduleModels.value.filter(x => x.left()).map(x => x.worker()))
// 未结清工人
const unsettledWorkers = computed(() => salaryModels.value.filter(x => x.unSettledRecords().length).map(x => x.worker()))

// setInterval(() => {
//   console.log(salaryModels.value);

// }, 2000)

// const settledWorkers = computed(() => salaryModels.value.filter(x => x.unSettledRecords.length === 0).map(x => x.worker()))
// 离职未结清工人
const leftUnsettledWorkers = computed(() => leftWorkers.value.filter(who => unsettledWorkers.value.findIndex(x => x.id === who.id) >= 0))
const leftSettledWorkers = computed(() => leftWorkers.value.filter(who => unsettledWorkers.value.findIndex(x => x.id === who.id) < 0))

function goDetail(row: ContactModel) {
  router.push(`/jobs/workers/detail?id=${row.id}`)
}

interface ModeName {
  mode: Mode
  name: string
}

const modeName: ModeName[] = [
  {
    mode: Mode.Day,
    name: '白班',
  },
  {
    mode: Mode.Night,
    name: '夜班',
  },
  {
    mode: Mode.NoSchedule,
    name: '其他安排',
  },
  {
    mode: Mode.LeftUnsettled,
    name: '离职未结',
  },
  {
    mode: Mode.LeftSettled,
    name: '离职结清',
  },
]
function getNameByMode(_mode: Mode): string | undefined {
  const target = modeName.find(x => x.mode === _mode)
  return target?.name
}

function getModeByName(_name: string): Mode {
  const target = modeName.find(x => x.name === _name)
  return target ? target.mode : Mode.None
}

function salaryFormatter(row: ContactModel) {
  const _records = records.value.filter(x => x.worker?.uniqueName() === row.uniqueName())
  _records.sort((a, b) => b.date.valueOf() - a.date.valueOf())
  const obr = lodash.first(_records.filter(x => x.action === JobAction.Start)) as JobRecordModel
  return obr.actionParams[0].toString()
}

function obTimeFormatter(row: ContactModel) {
  const _records = records.value.filter(x => x.worker?.uniqueName() === row.uniqueName())
  _records.sort((a, b) => b.date.valueOf() - a.date.valueOf())
  const obr = lodash.first(_records.filter(x => x.action === JobAction.Start)) as JobRecordModel
  return moment(obr.date).format('YYYY/MM/DD')
}

function scheduleFormatter(row: ContactModel) {
  return scheduleModels.value.find(x => x.worker().id === row.id)?.getSchedule()
}

function leftTimeFormatter(row: ContactModel) {
  const _records = records.value.filter(x => x.worker?.uniqueName() === row.uniqueName())
  _records.sort((a, b) => b.date.valueOf() - a.date.valueOf())
  const obr = lodash.first(_records.filter(x => x.action === JobAction.End)) as JobRecordModel
  return moment(obr.date).format('YYYY/MM/DD')
}

const tableData = computed(() => {
  if (mode.value === Mode.Day || mode.value === Mode.Night) {
    return mode.value === Mode.Day ? dayWorkers.value : nightWorkers.value
  }
  else if (mode.value === Mode.NoSchedule) {
    return otherWorkers.value
  }
  else if (mode.value === Mode.LeftUnsettled) {
    return leftUnsettledWorkers.value
  }
  else if (mode.value === Mode.LeftSettled) {
    return leftSettledWorkers.value
  }
  else {
    return []
  }
})

function goMode(_mode: Mode) {
  mode.value = _mode
  router.replace(`${route.path}?mode=${getNameByMode(_mode)}`)
}
</script>

<template>
  <div p4>
    <div mb2 w-full of-auto>
      <div style="width: max-content;">
        <Tag
          v-for="(item, index) in modeName" :key="index" type="primary" size="large" mr
          :plain="mode === item.mode ? false : true" @click="goMode(item.mode)"
        >
          {{ item.name }}
        </Tag>
      </div>
    </div>

    <div paper of-hidden p0>
      <table class="lx-table">
        <thead>
          <tr>
            <td>姓名</td>
            <td>工资</td>
            <td>入职时间</td>
            <td v-if="mode === Mode.NoSchedule">
              排班
            </td>
            <td v-if="mode === Mode.LeftUnsettled || mode === Mode.LeftSettled">
              离职时间
            </td>
          </tr>
        </thead>
        <tbody>
          <tr v-for="(item, index) in tableData" :key="index" @click="goDetail(item)">
            <td>
              {{ item.name }}
            </td>
            <td>
              {{ salaryFormatter(item) }}
            </td>
            <td>
              {{ obTimeFormatter(item) }}
            </td>
            <td v-if="mode === Mode.NoSchedule">
              {{ scheduleFormatter(item) }}
            </td>
            <td v-if="mode === Mode.LeftUnsettled || mode === Mode.LeftSettled">
              {{ leftTimeFormatter(item) }}
            </td>
          </tr>
        </tbody>
      </table>
    </div>
  </div>
</template>

<style scoped></style>

<route lang="yaml">
meta:
  title: 工人列表
</route>
